﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;

namespace CinemaDbLib
{
    public class DBObjectReflector
    {
        private Hashtable propHandlers;

        public DBObjectReflector()
        {
        }

        // adds a property handler to the object
        public void addPropertyHandler(string propertyName, DBPropertyReflector.getHandler GetHandler, DBPropertyReflector.setHandler SetHandler)
        {
            if (propHandlers == null)
            {
                propHandlers = new Hashtable();
            }

            DBPropertyReflector dbProp = new DBPropertyReflector(propertyName, GetHandler, SetHandler);
            propHandlers.Add(propertyName, dbProp);
        }

        public void setProperty(string propertyName, Object target, Object value)
        {
            try
            {
                if (propHandlers.ContainsKey(propertyName))
                {
                    DBPropertyReflector dbProp = (DBPropertyReflector)propHandlers[propertyName];
                    dbProp.setValue(target, value);
                }
                else
                {
                    PropertyInfo prop = target.GetType().GetProperty(propertyName);
                    prop.SetValue(target, value, null);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("DBObject Error [ Method: Set, Object Type: " + target.GetType().ToString() + ", PropertyName: " + propertyName + " ]: " + ex.Message);
            }
        }

        public Object getProperty(string propertyName, Object target)
        {
            try
            {
                if (propHandlers.ContainsKey(propertyName))
                {
                    DBPropertyReflector dbProp = (DBPropertyReflector)propHandlers[propertyName];
                    return dbProp.getValue(target);
                }
                else
                {
                    PropertyInfo prop = target.GetType().GetProperty(propertyName);
                    return prop.GetValue(target, null);
                }
            }
            catch ( Exception ex )
            {
                Console.WriteLine("DBObject Error [ Method: Get, Object Type: " + target.GetType().ToString() + ", PropertyName: " + propertyName + " ]: " + ex.Message);
                return null;
            }
        }
    }
}
